package tools

import (
	"api/config"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
)

type Consul struct {
	Host string
	Port int
}

func NewConsul(Host string, Port int) *Consul {
	return &Consul{
		Host: Host,
		Port: Port,
	}
}
func (c *Consul) RegisterConsul(name string, address string, port int, tags []string) error {
	registeration := new(api.AgentServiceRegistration)
	registeration.ID = uuid.NewString()
	registeration.Name = name
	registeration.Address = address
	registeration.Port = port
	registeration.Tags = tags
	registerErr := config.ConsulClient.Agent().ServiceRegister(registeration)
	if registerErr != nil {
		zap.S().Error(registerErr)
	}
	return registerErr
}
func (c *Consul) FilterService(name string) (map[string]*api.AgentService, error) {
	filter, err := config.ConsulClient.Agent().ServicesWithFilter(name)
	if err != nil {
		zap.S().Error(filter)
	}
	return filter, err
}
func (c *Consul) ServiceDeregister(serviceID string) error {
	err := config.ConsulClient.Agent().ServiceDeregister(serviceID)
	if err != nil {
		zap.S().Error(err)
	}
	return err
}
func (c *Consul) GetAllService() (map[string]*api.AgentService, error) {
	data, err := config.ConsulClient.Agent().Services()
	if err != nil {
		zap.S().Error(err)
	}
	return data, err
}
